package gui;

import classes.AusenciaTipo;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.GeralException;
import fachada.Fachada;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import rn.AusenciaTipoTableModel;

/**
 *
 * @author roberta.m.carvalho
 */
public class AusenciaTipoCadastrar extends javax.swing.JFrame {

    int x;
    ArrayList<AusenciaTipo> lista = new ArrayList<AusenciaTipo>();

    /** Creates new form AusenciaTipoCadastrar */
    public AusenciaTipoCadastrar() {
        initComponents();
        this.setIconImage(Login.icone.getImage());
        this.setLocationRelativeTo(null);
        carregarTabela();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupoDias = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textTipoAus = new javax.swing.JTextField();
        btSalvarTipo = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbTiposAus = new javax.swing.JTable();
        btExcluir = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Tipo de Ausência");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Tipo:");

        btSalvarTipo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btSalvarTipo.setText("Salvar");
        btSalvarTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarTipoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(68, 68, 68)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(textTipoAus, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btSalvarTipo)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textTipoAus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSalvarTipo))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Tipos Cadastrados:"));

        tbTiposAus.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Tipo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbTiposAus.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbTiposAusMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbTiposAus);

        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/excluir.png"))); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/editar.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(btExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btExcluir)
                        .addGap(18, 18, 18)
                        .addComponent(btAlterar))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btSalvarTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarTipoActionPerformed
        AusenciaTipo at = new AusenciaTipo();
        if (!textTipoAus.getText().trim().equals("")) {
            at.setNome(textTipoAus.getText());
            Fachada f = new Fachada();
            try {
                f.inserir(at);
                textTipoAus.setText("");
                carregarTabela();
            } catch (ConexaoException e) {
                JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
            } catch (ConsultaException e) {
                JOptionPane.showMessageDialog(null, "Não foi possível inserir o novo Tipo de Ausência!\n" + e);
            } catch (GeralException e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
                this.repaint();
            }
        }
    }//GEN-LAST:event_btSalvarTipoActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir?", "Alerta!", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            int size = tbTiposAus.getSelectedRowCount();
            if (size > 1) {
                JOptionPane.showMessageDialog(null, "Selecione apenas um tipo por vez!");
                tbTiposAus.setSelectionMode(1);
            } else {
                AusenciaTipo at = new AusenciaTipo();
                Fachada f = new Fachada();
                try {
                    int r = tbTiposAus.getSelectedRow();
                    AusenciaTipoTableModel ltm = new AusenciaTipoTableModel(carregarLista());
                    at = ltm.get(r);
                    f.deletar(at);
                    carregarTabela();
                } catch (ConexaoException e) {
                    JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
                } catch (ConsultaException e) {
                    JOptionPane.showMessageDialog(null, "Tipo em uso!");
                }
            }
        } else {
            this.repaint();
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    private void tbTiposAusMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbTiposAusMouseClicked
        if (evt.getClickCount() == 2 && evt.getButton() == MouseEvent.BUTTON1) {//se o clique for duplo  
            x = tbTiposAus.getSelectedRow(); //Pega o índice da linha selecionada.  
            AusenciaTipoTableModel ltm = new AusenciaTipoTableModel(carregarLista());
            AusenciaTipo at = new AusenciaTipo();
            at = ltm.get(x);
            textTipoAus.setText(at.getNome());
        }
    }//GEN-LAST:event_tbTiposAusMouseClicked

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        Fachada f = new Fachada();
        AusenciaTipo at = new AusenciaTipo();
        int r = tbTiposAus.getSelectedRow();
        AusenciaTipoTableModel ltm = new AusenciaTipoTableModel(carregarLista());
        try {
            at.setCodTipo(ltm.get(r).getCodTipo());
            at.setNome(textTipoAus.getText());
            f.alterarTipo(at);
            JOptionPane.showMessageDialog(null, "Alterado com sucesso!");
            carregarTabela();
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível alterar Tipo de Ausência!\n" + ex);
        } catch (GeralException ex) {
        }

    }//GEN-LAST:event_btAlterarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AusenciaTipoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AusenciaTipoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AusenciaTipoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AusenciaTipoCadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new AusenciaTipoCadastrar().setVisible(true);
            }
        });
    }

    public final void carregarTabela() {

        tbTiposAus.setModel(new AusenciaTipoTableModel(carregarLista()));
    }

    public ArrayList<AusenciaTipo> carregarLista() {
        Fachada f = new Fachada();
        ArrayList<AusenciaTipo> lista = new ArrayList<AusenciaTipo>();
        try {
            lista = f.listarTipo();
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tabela.\n" + ex);
        }
        return lista;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btSalvarTipo;
    private javax.swing.ButtonGroup grupoDias;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbTiposAus;
    private javax.swing.JTextField textTipoAus;
    // End of variables declaration//GEN-END:variables
}
